#coding:utf8
'''python3 code support python2
author's email: chenyan@feling.net

在这里编写各url对应的方法，运行httpd4t.py的时候，这里的方法会被加载进去

+ 用装饰器描述method和uri
+ ctx参数是http.server.BaseHTTPRequestHandler的子类（httpd4t.RequestHandler）的上下文（不要用它的wfile。用return来代替wfile）
+ return的str会作为http响应的内容
+ return None或空字符串会响应500报文
'''
import logging
logging.basicConfig(level=logging.INFO,
                format='%(asctime)s [line:%(lineno)d] %(levelname)s %(message)s',
                datefmt='%M:%S',
                )

from httpd4t import POST, GET
import os
try:
    import pymysql as mysql
    logging.info('use pymysql3')
except:
    from mysql import connector as mysql
    logging.info('use mysql-connector-python2')

def get_post_data(headers,rfile):
    data_str = ''
    if 'Content-Length' in headers:
        data_str = rfile.read(int(headers['Content-Length'])).decode('utf-8')
    else:
        while True:
            buf = rfile.read(4096)
            data_str = data_str + buf.decode('utf-8')
            if not buf:
                break
    data_dic = {}
    for i in data_str.split('&'):
        kv = i.split('=')
        if len(kv)==2:
            k = kv[0]
            v = kv[1]
            data_dic[k] = v
    return data_dic

def get_get_data(path):
    uri = path.split('?')
    if len(uri)!=2:
        return ''
    data_str = uri[1]
    data_dic = {}
    for i in data_str.split('&'):
        kv = i.split('=')
        if len(kv)==2:
            k = kv[0]
            v = kv[1]
            data_dic[k] = v
    return data_dic


@GET('/click_count')
def click_count(ctx):
    data = get_get_data(ctx.path)
    if 'post_id' in data and data['post_id']:
        conn = mysql.connect(host='localhost', port=3306,user='root',passwd='test',db='feling')
        cur = conn.cursor()
        cur.execute("SELECT `count` FROM click_count WHERE `post_id`='%s';" % data['post_id'])
        r=cur.fetchone()
        count = r[0] if r else 0
        if count:
            cur.execute("UPDATE `click_count` SET `count`='%s' WHERE `post_id`='%s';" % (count+1, data['post_id']) )
        else:
            count=1
            cur.execute("INSERT INTO `click_count` (`post_id`, `count`) VALUES ('%s', '%s');" % (data['post_id'] , 2) )
        conn.commit()
        cur.close()
        conn.close()

        return '''document.getElementById("click_count").innerHTML="'''+ str(count) +'''次浏览";'''
    return ';'
